import axios, { AxiosResponse } from 'axios'
import Event from './Event'
import { SHOW_LOADING, HIDE_LOADING, SHOW_MSG } from './Event'
export function ajaxPost(url: string, noLoading: boolean, data?: any) {
  return new Promise((resolver) => {
    if (!noLoading) {
      showLoading(data?.keepLoadingTip)
    }
    axios({
      method: 'post',
      headers: {
        'Content-Type': 'text/plain;charset=UTF-8'
      },
      url,
      data
    })
      .then((res) => {
        resolver(res.data)
      })
      .catch((res) => {
        catchAjaxException(res)
      })
      .finally(() => {
        if (!noLoading) {
          hideLoading()
        }
      })
  })
}

export function ajaxDownloadFile(url: string) {
  return new Promise((resolver: (res: AxiosResponse) => void) => {
    showLoading()
    axios({
      method: 'get',
      headers: {
        'Content-Type': 'text/plain;charset=UTF-8'
      },
      url
    })
      .then((res: AxiosResponse) => {
        resolver(res)
      })
      .catch((res) => {
        catchAjaxException(res)
      })
      .finally(() => {
        hideLoading()
      })
  })
}

export function postForOpenUrl(url:string, parameters:any, target: string) {
  const form = document.createElement("form");
  form.action = url;
  form.target = target;
  form.method = "post";
  form.style.display = "none";
  for (let key in parameters) {
    const item = document.createElement("textarea");
    item.name = key;
    item.value = parameters[key];
    form.appendChild(item);
  }
  document.body.appendChild(form);
  form.submit();
  document.body.removeChild(form);
}

function catchAjaxException(res: any) {
  let stack = null
  let errorMsg = '服务端未响应，请检查服务器是否处于运行状态'
  const response = res.response
  if (response && response.status === 886) {
    const tip = decodeURI('产品试用到期或License过期')
    showAlert(tip, decodeURI('产品使用授权提示'))
    return
  }
  if (response && response.data) {
    const data = res.response.data
    errorMsg = data.errorMsg || '未知错误'
    stack = data.stack
  }
  setTimeout(() => {
    let msg = errorMsg
    if (stack) {
      msg += '<br>' + stack
    }
    showAlert(msg, '服务端错误')
  }, 1)
}

export function showAlert(msg: string, title?: string) {
  Event.emit(SHOW_MSG, { msg, title })
}

export function showLoading(keepLoadingTip?: boolean) {
  Event.emit(SHOW_LOADING, keepLoadingTip)
}

export function hideLoading() {
  Event.emit(HIDE_LOADING)
}

export function dragElement(event: MouseEvent): void {
  let target = event.target as HTMLElement
  target = target.parentElement as HTMLElement
  const style = window.getComputedStyle(target)
  const windowWidth = document.documentElement.clientWidth
  const windowHeight = document.documentElement.clientHeight
  let x = event.clientX
  let y = event.clientY

  const move = (e: MouseEvent): void => {
    const ex = e.clientX
    const ey = e.clientY
    let disX = ex - x
    let disY = ey - y
    disX = parseInt(style.left) + disX
    disY = parseInt(style.top) + disY
    if (disX < 0) {
      disX = 0
    }
    if (disX > windowWidth) {
      disX = windowWidth
    }
    if (disY < 60) {
      disY = 60
    }
    if (disY > windowHeight) {
      disY = windowHeight
    }
    target.style.left = disX + 'px'
    target.style.top = disY + 'px'
    x = ex
    y = ey
  }
  const end = () => {
    document.documentElement.removeEventListener('mousemove', move)
    document.documentElement.removeEventListener('mouseup', end)
  }
  document.documentElement.addEventListener('mousemove', move)
  document.documentElement.addEventListener('mouseup', end)
}
